home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / shells / scsh-0.4 / scsh-0 / scsh-0.4.2 / emacs / comint.el < prev    next >
Text File  |  1995-10-13  |  58KB  |  1,373 lines

  1. ;;; -*-Emacs-Lisp-*- General command interpreter in a window stuff
  2. ;;; Copyright Olin Shivers (1988).
  3. ;;; Please imagine a long, tedious, legalistic 5-page gnu-style copyright
  4. ;;; notice appearing here to the effect that you may use this code any
  5. ;;; way you like, as long as you don't charge money for it, remove this
  6. ;;; notice, or hold me liable for its results.
  7.  
  8. ;;; The changelog is at the end of this file.
  9.  
  10. ;;; Please send me bug reports, bug fixes, and extensions, so that I can
  11. ;;; merge them into the master source.
  12. ;;;     - Olin Shivers (shivers@cs.cmu.edu)
  13.  
  14. ;;; This hopefully generalises shell mode, lisp mode, tea mode, soar mode,...
  15. ;;; This file defines a general command-interpreter-in-a-buffer package
  16. ;;; (comint mode). The idea is that you can build specific process-in-a-buffer
  17. ;;; modes on top of comint mode -- e.g., lisp, shell, scheme, T, soar, ....
  18. ;;; This way, all these specific packages share a common base functionality, 
  19. ;;; and a common set of bindings, which makes them easier to use (and
  20. ;;; saves code, implementation time, etc., etc.).
  21.  
  22. ;;; Several packages are already defined using comint mode:
  23. ;;; - cmushell.el defines a shell-in-a-buffer mode.
  24. ;;; - cmulisp.el defines a simple lisp-in-a-buffer mode.
  25. ;;; Cmushell and cmulisp mode are similar to, and intended to replace,
  26. ;;; their counterparts in the standard gnu emacs release (in shell.el). 
  27. ;;; These replacements are more featureful, robust, and uniform than the 
  28. ;;; released versions. The key bindings in lisp mode are also more compatible
  29. ;;; with the bindings of Hemlock and Zwei (the Lisp Machine emacs).
  30. ;;;
  31. ;;; - The file cmuscheme.el defines a scheme-in-a-buffer mode.
  32. ;;; - The file tea.el tunes scheme and inferior-scheme modes for T.
  33. ;;; - The file soar.el tunes lisp and inferior-lisp modes for Soar.
  34. ;;; - cmutex.el defines tex and latex modes that invoke tex, latex, bibtex,
  35. ;;;   previewers, and printers from within emacs.
  36. ;;; - background.el allows csh-like job control inside emacs.
  37. ;;; It is pretty easy to make new derived modes for other processes.
  38.  
  39. ;;; For documentation on the functionality provided by comint mode, and
  40. ;;; the hooks available for customising it, see the comments below.
  41. ;;; For further information on the standard derived modes (shell, 
  42. ;;; inferior-lisp, inferior-scheme, ...), see the relevant source files.
  43.  
  44. ;;; For hints on converting existing process modes (e.g., tex-mode,
  45. ;;; background, dbx, gdb, kermit, prolog, telnet) to use comint-mode
  46. ;;; instead of shell-mode, see the notes at the end of this file.
  47.  
  48. (provide 'comint)
  49. (defconst comint-version "2.02")
  50.  
  51.  
  52. ;;; Brief Command Documentation:
  53. ;;;============================================================================
  54. ;;; Comint Mode Commands: (common to all derived modes, like cmushell & cmulisp
  55. ;;; mode)
  56. ;;;
  57. ;;; m-p        comint-previous-input            Cycle backwards in input history
  58. ;;; m-n        comint-next-input                  Cycle forwards
  59. ;;; m-s     comint-previous-similar-input   Previous similar input
  60. ;;; c-c r   comint-previous-input-matching  Search backwards in input history
  61. ;;; return  comint-send-input
  62. ;;; c-a     comint-bol                      Beginning of line; skip prompt.
  63. ;;; c-d        comint-delchar-or-maybe-eof     Delete char unless at end of buff.
  64. ;;; c-c c-u comint-kill-input                ^u
  65. ;;; c-c c-w backward-kill-word            ^w
  66. ;;; c-c c-c comint-interrupt-subjob         ^c
  67. ;;; c-c c-z comint-stop-subjob                ^z
  68. ;;; c-c c-\ comint-quit-subjob                ^\
  69. ;;; c-c c-o comint-kill-output            Delete last batch of process output
  70. ;;; c-c c-r comint-show-output            Show last batch of process output
  71. ;;;
  72. ;;; Not bound by default in comint-mode
  73. ;;; send-invisible            Read a line w/o echo, and send to proc
  74. ;;; (These are bound in shell-mode)
  75. ;;; comint-dynamic-complete        Complete filename at point.
  76. ;;; comint-dynamic-list-completions    List completions in help buffer.
  77. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  78. ;;;                    replace with expanded/completed name.
  79. ;;; comint-kill-subjob            No mercy.
  80. ;;; comint-continue-subjob        Send CONT signal to buffer's process
  81. ;;;                    group. Useful if you accidentally
  82. ;;;                    suspend your process (with C-c C-z).
  83. ;;;
  84. ;;; Bound for RMS -- I prefer the input history stuff, but you might like 'em.
  85. ;;; m-P       comint-msearch-input        Search backwards for prompt
  86. ;;; m-N    comint-psearch-input        Search forwards for prompt
  87. ;;; C-cR   comint-msearch-input-matching Search backwards for prompt & string
  88.  
  89. ;;; comint-mode-hook is the comint mode hook. Basically for your keybindings.
  90. ;;; comint-load-hook is run after loading in this package.
  91.  
  92.  
  93. ;;; Buffer Local Variables:
  94. ;;;============================================================================
  95. ;;; Comint mode buffer local variables:
  96. ;;;     comint-prompt-regexp    - string       comint-bol uses to match prompt.
  97. ;;;     comint-last-input-end   - marker       For comint-kill-output command
  98. ;;;     input-ring-size         - integer      For the input history
  99. ;;;     input-ring              - ring             mechanism
  100. ;;;     input-ring-index        - marker           ...
  101. ;;;     comint-last-input-match - string           ...
  102. ;;;     comint-get-old-input    - function     Hooks for specific 
  103. ;;;     comint-input-sentinel   - function         process-in-a-buffer
  104. ;;;     comint-input-filter     - function         modes.
  105. ;;;     comint-input-send    - function
  106. ;;;     comint-eol-on-send    - boolean
  107.  
  108. (defvar comint-prompt-regexp "^"
  109.   "Regexp to recognise prompts in the inferior process.
  110. Defaults to \"^\", the null string at BOL.
  111.  
  112. Good choices:
  113.   Canonical Lisp: \"^[^> ]*>+:? *\" (Lucid, franz, kcl, T, cscheme, oaklisp)
  114.   Lucid Common Lisp: \"^\\(>\\|\\(->\\)+\\) *\"
  115.   franz: \"^\\(->\\|<[0-9]*>:\\) *\"
  116.   kcl: \"^>+ *\"
  117.   shell: \"^[^#$%>]*[#$%>] *\"
  118.   T: \"^>+ *\"
  119.  
  120. This is a good thing to set in mode hooks.")
  121.  
  122. (defvar input-ring-size 30
  123.   "Size of input history ring.")
  124.  
  125. ;;; Here are the per-interpreter hooks.
  126. (defvar comint-get-old-input (function comint-get-old-input-default)
  127.   "Function that submits old text in comint mode.
  128. This function is called when return is typed while the point is in old text.
  129. It returns the text to be submitted as process input.  The default is
  130. comint-get-old-input-default, which grabs the current line, and strips off
  131. leading text matching comint-prompt-regexp")
  132.  
  133. (defvar comint-input-sentinel (function ignore)
  134.   "Called on each input submitted to comint mode process by comint-send-input.
  135. Thus it can, for instance, track cd/pushd/popd commands issued to the csh.")
  136.  
  137. (defvar comint-input-filter
  138.   (function (lambda (str) (not (string-match "\\`\\s *\\'" str))))
  139.   "Predicate for filtering additions to input history.
  140. Only inputs answering true to this function are saved on the input
  141. history list. Default is to save anything that isn't all whitespace")
  142.  
  143. (defvar comint-input-sender (function comint-simple-send)
  144.   "Function to actually send to PROCESS the STRING submitted by user.
  145. Usually this is just 'comint-simple-send, but if your mode needs to 
  146. massage the input string, this is your hook. This is called from
  147. the user command comint-send-input. comint-simple-send just sends
  148. the string plus a newline.")
  149.  
  150. (defvar comint-eol-on-send 'T
  151.   "If non-nil, then jump to the end of the line before sending input to process.
  152. See COMINT-SEND-INPUT")
  153.  
  154. (defvar comint-mode-hook '()
  155.   "Called upon entry into comint-mode
  156. This is run before the process is cranked up.")
  157.  
  158. (defvar comint-exec-hook '()
  159.   "Called each time a process is exec'd by comint-exec.
  160. This is called after the process is cranked up.  It is useful for things that
  161. must be done each time a process is executed in a comint-mode buffer (e.g.,
  162. (process-kill-without-query)). In contrast, the comint-mode-hook is only
  163. executed once when the buffer is created.")
  164.  
  165. (defvar comint-mode-map nil)
  166.  
  167. (defun comint-mode ()
  168.   "Major mode for interacting with an inferior interpreter.
  169. Interpreter name is same as buffer name, sans the asterisks.
  170. Return at end of buffer sends line as input.
  171. Return not at end copies rest of line to end and sends it.
  172. Setting mode variable comint-eol-on-send means jump to the end of the line
  173. before submitting new input.
  174.  
  175. This mode is typically customised to create inferior-lisp-mode,
  176. shell-mode, etc.. This can be done by setting the hooks
  177. comint-input-sentinel, comint-input-filter, comint-input-sender and
  178. comint-get-old-input to appropriate functions, and the variable
  179. comint-prompt-regexp to the appropriate regular expression.
  180.  
  181. An input history is maintained of size input-ring-size, and
  182. can be accessed with the commands comint-next-input [\\[comint-next-input]] and 
  183. comint-previous-input [\\[comint-previous-input]]. Commands not keybound by
  184. default are send-invisible, comint-dynamic-complete, and 
  185. comint-list-dynamic-completions.
  186.  
  187. If you accidentally suspend your process, use \\[comint-continue-subjob]
  188. to continue it.
  189.  
  190. \\{comint-mode-map}
  191.  
  192. Entry to this mode runs the hooks on comint-mode-hook"
  193.   (interactive)
  194.   (let ((old-ring (and (assq 'input-ring (buffer-local-variables))
  195.                (boundp 'input-ring)
  196.                input-ring))
  197.     (old-ptyp comint-ptyp)) ; preserve across local var kill. gross.
  198. ;   (kill-all-local-variables) ; Removed 1/15/90 Olin
  199.     (setq major-mode 'comint-mode)
  200.     (setq mode-name "Comint")
  201.     (setq mode-line-process '(": %s"))
  202.     (use-local-map comint-mode-map)
  203.     (make-local-variable 'comint-last-input-end)
  204.     (setq comint-last-input-end (make-marker))
  205.     (make-local-variable 'comint-last-input-match)
  206.     (setq comint-last-input-match "")
  207.     (make-local-variable 'comint-prompt-regexp) ; Don't set; default
  208.     (make-local-variable 'input-ring-size)      ; ...to global val.
  209.     (make-local-variable 'input-ring)
  210.     (make-local-variable 'input-ring-index)
  211.     (setq input-ring-index 0)
  212.     (make-local-variable 'comint-get-old-input)
  213.     (make-local-variable 'comint-input-sentinel)
  214.     (make-local-variable 'comint-input-filter)  
  215.     (make-local-variable 'comint-input-sender)
  216.     (make-local-variable 'comint-eol-on-send)
  217.     (make-local-variable 'comint-ptyp)
  218.     (setq comint-ptyp old-ptyp)
  219.     (make-local-variable 'comint-exec-hook)
  220.     (run-hooks 'comint-mode-hook)
  221.     ;Do this after the hook so the user can mung INPUT-RING-SIZE w/his hook.
  222.     ;The test is so we don't lose history if we run comint-mode twice in
  223.     ;a buffer.
  224.     (setq input-ring (if (ring-p old-ring) old-ring
  225.              (make-ring input-ring-size)))))
  226.  
  227. ;;; The old-ptyp stuff above is because we have to preserve the value of
  228. ;;; comint-ptyp across calls to comint-mode, in spite of the
  229. ;;; kill-all-local-variables that it does. Blech. Hopefully, this will all
  230. ;;; go away when a later release fixes the signalling bug.
  231. ;;; (Later: I removed the kill-all-local-variables, but have left this
  232. ;;; other code in place just in case I reverse myself.)
  233.  
  234. (if comint-mode-map
  235.     nil
  236.   (setq comint-mode-map (make-sparse-keymap))
  237.   (define-key comint-mode-map "\ep" 'comint-previous-input)
  238.   (define-key comint-mode-map "\en" 'comint-next-input)
  239.   (define-key comint-mode-map "\es" 'comint-previous-similar-input)
  240.   (define-key comint-mode-map "\C-m" 'comint-send-input)
  241.   (define-key comint-mode-map "\C-d" 'comint-delchar-or-maybe-eof)
  242.   (define-key comint-mode-map "\C-a" 'comint-bol)
  243.   (define-key comint-mode-map "\C-c\C-u" 'comint-kill-input)
  244.   (define-key comint-mode-map "\C-c\C-w" 'backward-kill-word)
  245.   (define-key comint-mode-map "\C-c\C-c" 'comint-interrupt-subjob)
  246.   (define-key comint-mode-map "\C-c\C-z" 'comint-stop-subjob)
  247.   (define-key comint-mode-map "\C-c\C-\\" 'comint-quit-subjob)
  248.   (define-key comint-mode-map "\C-c\C-o" 'comint-kill-output)
  249.   (define-key comint-mode-map "\C-cr"    'comint-previous-input-matching)
  250.   (define-key comint-mode-map "\C-c\C-r" 'comint-show-output)
  251.   ;;; prompt-search commands commented out 3/90 -Olin
  252. ; (define-key comint-mode-map "\eP" 'comint-msearch-input)
  253. ; (define-key comint-mode-map "\eN" 'comint-psearch-input)
  254. ; (define-key comint-mode-map "\C-cR" 'comint-msearch-input-matching)
  255.   )
  256.  
  257.  
  258. ;;; This function is used to make a full copy of the comint mode map,
  259. ;;; so that client modes won't interfere with each other. This function
  260. ;;; isn't necessary in emacs 18.5x, but we keep it around for 18.4x versions.
  261. (defun full-copy-sparse-keymap (km)
  262.   "Recursively copy the sparse keymap KM"
  263.   (cond ((consp km)
  264.      (cons (full-copy-sparse-keymap (car km))
  265.            (full-copy-sparse-keymap (cdr km))))
  266.     (t km)))
  267.  
  268. (defun comint-check-proc (buffer)
  269.   "True if there is a process associated w/buffer BUFFER, and
  270. it is alive (status RUN or STOP). BUFFER can be either a buffer or the
  271. name of one"
  272.   (let ((proc (get-buffer-process buffer)))
  273.     (and proc (memq (process-status proc) '(run stop)))))
  274.  
  275. ;;; Note that this guy, unlike shell.el's make-shell, barfs if you pass it ()
  276. ;;; for the second argument (program).
  277. (defun make-comint (name program &optional startfile &rest switches)
  278.   (let ((buffer (get-buffer-create (concat "*" name "*"))))
  279.     ;; If no process, or nuked process, crank up a new one and put buffer in
  280.     ;; comint mode. Otherwise, leave buffer and existing process alone.
  281.     (cond ((not (comint-check-proc buffer))
  282.        (save-excursion
  283.          (set-buffer buffer)
  284.          (comint-mode)) ; Install local vars, mode, keymap, ...
  285.        (comint-exec buffer name program startfile switches)))
  286.     buffer))
  287.  
  288. (defvar comint-ptyp t
  289.   "True if communications via pty; false if by pipe. Buffer local.
  290. This is to work around a bug in emacs process signalling.")
  291.  
  292. (defun comint-exec (buffer name command startfile switches)
  293.   "Fires up a process in buffer for comint modes.
  294. Blasts any old process running in the buffer. Doesn't set the buffer mode.
  295. You can use this to cheaply run a series of processes in the same comint
  296. buffer. The hook comint-exec-hook is run after each exec."
  297.   (save-excursion
  298.     (set-buffer buffer)
  299.     (let ((proc (get-buffer-process buffer)))    ; Blast any old process.
  300.       (if proc (delete-process proc)))
  301.     ;; Crank up a new process
  302.     (let ((proc (comint-exec-1 name buffer command switches)))
  303.       (make-local-variable 'comint-ptyp)
  304.       (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
  305.       ;; Jump to the end, and set the process mark.
  306.       (goto-char (point-max))
  307.       (set-marker (process-mark proc) (point))
  308.       ;; Feed it the startfile.
  309.       (cond (startfile
  310.          ;;This is guaranteed to wait long enough
  311.          ;;but has bad results if the comint does not prompt at all
  312.          ;;         (while (= size (buffer-size))
  313.          ;;           (sleep-for 1))
  314.          ;;I hope 1 second is enough!
  315.          (sleep-for 1)
  316.          (goto-char (point-max))
  317.          (insert-file-contents startfile)
  318.          (setq startfile (buffer-substring (point) (point-max)))
  319.          (delete-region (point) (point-max))
  320.          (comint-send-string proc startfile)))
  321.     (run-hooks 'comint-exec-hook)
  322.     buffer)))
  323.  
  324. ;;; This auxiliary function cranks up the process for comint-exec in
  325. ;;; the appropriate environment. It is twice as long as it should be
  326. ;;; because emacs has two distinct mechanisms for manipulating the
  327. ;;; process environment, selected at compile time with the
  328. ;;; MAINTAIN-ENVIRONMENT #define. In one case, process-environment
  329. ;;; is bound; in the other it isn't.
  330.  
  331. (defun comint-exec-1 (name buffer command switches)
  332.   (if (boundp 'process-environment) ; Not a completely reliable test.
  333.       (let ((process-environment
  334.          (comint-update-env process-environment
  335.                 (list (format "TERMCAP=emacs:co#%d:tc=unknown"
  336.                           (screen-width))
  337.                       "TERM=emacs"
  338.                       "EMACS=t"))))
  339.     (apply 'start-process name buffer command switches))
  340.  
  341.       (let ((tcapv (getenv "TERMCAP"))
  342.         (termv (getenv "TERM"))
  343.         (emv   (getenv "EMACS")))
  344.     (unwind-protect
  345.          (progn (setenv "TERMCAP" (format "emacs:co#%d:tc=unknown"
  346.                           (screen-width)))
  347.             (setenv "TERM" "emacs")
  348.             (setenv "EMACS" "t")
  349.             (apply 'start-process name buffer command switches))
  350.       (setenv "TERMCAP" tcapv)
  351.       (setenv "TERM"    termv)
  352.       (setenv "EMACS"   emv)))))
  353.          
  354.  
  355.  
  356. ;; This is just (append new old-env) that compresses out shadowed entries.
  357. ;; It's also pretty ugly, mostly due to elisp's horrible iteration structures.
  358. (defun comint-update-env (old-env new)
  359.   (let ((ans (reverse new))
  360.     (vars (mapcar (function (lambda (vv)
  361.             (and (string-match "^[^=]*=" vv)
  362.                  (substring vv 0 (match-end 0)))))
  363.               new)))
  364.     (while old-env
  365.       (let* ((vv (car old-env)) ; vv is var=value
  366.          (var (and (string-match "^[^=]*=" vv)
  367.                (substring vv 0 (match-end 0)))))
  368.     (setq old-env (cdr old-env))
  369.     (cond ((not (and var (comint-mem var vars)))
  370.            (if var (setq var (cons var vars)))
  371.            (setq ans (cons vv ans))))))
  372.     (nreverse ans)))
  373.  
  374. ;;; This should be in emacs, but it isn't.
  375. (defun comint-mem (item list &optional elt=)
  376.   "Test to see if ITEM is equal to an item in LIST.
  377. Option comparison function ELT= defaults to equal."
  378.   (let ((elt= (or elt= (function equal)))
  379.     (done nil))
  380.     (while (and list (not done))
  381.       (if (funcall elt= item (car list))
  382.       (setq done list)
  383.       (setq list (cdr list))))
  384.     done))
  385.  
  386.  
  387. ;;; Ring Code
  388. ;;;============================================================================
  389. ;;; This code defines a ring data structure. A ring is a 
  390. ;;;     (hd-index tl-index . vector) 
  391. ;;; list. You can insert to, remove from, and rotate a ring. When the ring
  392. ;;; fills up, insertions cause the oldest elts to be quietly dropped.
  393. ;;;
  394. ;;; HEAD = index of the newest item on the ring.
  395. ;;; TAIL = index of the oldest item on the ring.
  396. ;;;
  397. ;;; These functions are used by the input history mechanism, but they can
  398. ;;; be used for other purposes as well.
  399.  
  400. (defun ring-p (x) 
  401.   "T if X is a ring; NIL otherwise."
  402.   (and (consp x) (integerp (car x))
  403.        (consp (cdr x)) (integerp (car (cdr x)))
  404.        (vectorp (cdr (cdr x)))))
  405.  
  406. (defun make-ring (size)
  407.   "Make a ring that can contain SIZE elts"
  408.   (cons 1 (cons 0 (make-vector (+ size 1) nil))))
  409.  
  410. (defun ring-plus1 (index veclen)
  411.   "INDEX+1, with wraparound"
  412.   (let ((new-index (+ index 1)))
  413.     (if (= new-index veclen) 0 new-index)))
  414.  
  415. (defun ring-minus1 (index veclen)
  416.   "INDEX-1, with wraparound"
  417.   (- (if (= 0 index) veclen index) 1))
  418.  
  419. (defun ring-length (ring)
  420.   "Number of elts in the ring."
  421.   (let ((hd (car ring)) (tl (car (cdr ring)))  (siz (length (cdr (cdr ring)))))
  422.     (let ((len (if (<= hd tl) (+ 1 (- tl hd)) (+ 1 tl (- siz hd)))))
  423.       (if (= len siz) 0 len))))
  424.  
  425. (defun ring-empty-p (ring)
  426.   (= 0 (ring-length ring)))
  427.  
  428. (defun ring-insert (ring item)
  429.   "Insert a new item onto the ring. If the ring is full, dump the oldest
  430. item to make room."       
  431.   (let* ((vec (cdr (cdr ring)))  (len (length vec))
  432.      (new-hd (ring-minus1 (car ring) len)))
  433.       (setcar ring new-hd)
  434.       (aset vec new-hd item)
  435.       (if (ring-empty-p ring) ;overflow -- dump one off the tail.
  436.       (setcar (cdr ring) (ring-minus1 (car (cdr ring)) len)))))
  437.  
  438. (defun ring-remove (ring)
  439.   "Remove the oldest item retained on the ring."
  440.   (if (ring-empty-p ring) (error "Ring empty")
  441.       (let ((tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  442.     (set-car (cdr ring) (ring-minus1 tl (length vec)))
  443.     (aref vec tl))))
  444.  
  445. ;;; This isn't actually used in this package. I just threw it in in case
  446. ;;; someone else wanted it. If you want rotating-ring behavior on your history
  447. ;;; retrieval (analagous to kill ring behavior), this function is what you
  448. ;;; need. I should write the yank-input and yank-pop-input-or-kill to go with
  449. ;;; this, and not bind it to a key by default, so it would be available to
  450. ;;; people who want to bind it to a key. But who would want it? Blech.
  451. (defun ring-rotate (ring n)
  452.   (if (not (= n 0))
  453.       (if (ring-empty-p ring) ;Is this the right error check?
  454.       (error "ring empty")
  455.       (let ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring))))
  456.         (let ((len (length vec)))
  457.           (while (> n 0)
  458.         (setq tl (ring-plus1 tl len))
  459.         (aset ring tl (aref ring hd))
  460.         (setq hd (ring-plus1 hd len))
  461.         (setq n (- n 1)))
  462.           (while (< n 0)
  463.         (setq hd (ring-minus1 hd len))
  464.         (aset vec hd (aref vec tl))
  465.         (setq tl (ring-minus1 tl len))
  466.         (setq n (- n 1))))
  467.         (set-car ring hd)
  468.         (set-car (cdr ring) tl)))))
  469.  
  470. (defun comint-mod (n m)
  471.   "Returns N mod M. M is positive. Answer is guaranteed to be non-negative, 
  472. and less than m."
  473.   (let ((n (% n m)))
  474.     (if (>= n 0) n
  475.     (+ n
  476.        (if (>= m 0) m (- m)))))) ; (abs m)
  477.  
  478. (defun ring-ref (ring index)
  479.   (let ((numelts (ring-length ring)))
  480.     (if (= numelts 0) (error "indexed empty ring")
  481.     (let* ((hd (car ring))  (tl (car (cdr ring)))  (vec (cdr (cdr ring)))
  482.            (index (comint-mod index numelts))
  483.            (vec-index (comint-mod (+ index hd) 
  484.                       (length vec))))
  485.       (aref vec vec-index)))))
  486.  
  487.  
  488. ;;; Input history retrieval commands
  489. ;;; M-p -- previous input    M-n -- next input
  490. ;;; C-c r -- previous input matching
  491. ;;; ===========================================================================
  492.  
  493. (defun comint-previous-input (arg)
  494.   "Cycle backwards through input history."
  495.   (interactive "*p")
  496.   (let ((len (ring-length input-ring)))
  497.     (cond ((<= len 0)
  498.        (message "Empty input ring")
  499.        (ding))
  500.       ((not (comint-after-pmark-p))
  501.        (message "Not after process mark")
  502.        (ding))
  503.       (t
  504.        (cond ((eq last-command 'comint-previous-input)
  505.           (delete-region (mark) (point)))
  506.          ((eq last-command 'comint-previous-similar-input)
  507.           (delete-region 
  508.            (process-mark (get-buffer-process (current-buffer)))
  509.            (point)))
  510.          (t                          
  511.           (setq input-ring-index
  512.             (if (> arg 0) -1
  513.                 (if (< arg 0) 1 0)))
  514.           (push-mark (point))))
  515.        (setq input-ring-index (comint-mod (+ input-ring-index arg) len))
  516.        (message "%d" (1+ input-ring-index))
  517.        (insert (ring-ref input-ring input-ring-index))
  518.        (setq this-command 'comint-previous-input)))))
  519.      
  520. (defun comint-next-input (arg)
  521.   "Cycle forwards through input history."
  522.   (interactive "*p")
  523.   (comint-previous-input (- arg)))
  524.  
  525. (defvar comint-last-input-match ""
  526.   "Last string searched for by comint input history search, for defaulting.
  527. Buffer local variable.") 
  528.  
  529. (defun comint-previous-input-matching (str)
  530.   "Searches backwards through input history for substring match."
  531.   (interactive (let* ((last-command last-command) ; preserve around r-f-m
  532.               (s (read-from-minibuffer 
  533.              (format "Command substring (default %s): "
  534.                  comint-last-input-match))))
  535.          (list (if (string= s "") comint-last-input-match s))))
  536. ; (interactive "sCommand substring: ")
  537.   (setq comint-last-input-match str) ; update default
  538.   (if (not (eq last-command 'comint-previous-input))
  539.       (setq input-ring-index -1))
  540.   (let ((str (regexp-quote str))
  541.         (len (ring-length input-ring))
  542.     (n (+ input-ring-index 1)))
  543.     (while (and (< n len) (not (string-match str (ring-ref input-ring n))))
  544.       (setq n (+ n 1)))
  545.     (cond ((< n len)
  546.        (comint-previous-input (- n input-ring-index)))
  547.       (t (if (eq last-command 'comint-previous-input) 
  548.          (setq this-command 'comint-previous-input))
  549.          (message "Not found.")
  550.          (ding)))))
  551.  
  552.  
  553. ;;; These next three commands are alternatives to the input history commands
  554. ;;; -- comint-next-input, comint-previous-input and
  555. ;;; comint-previous-input-matching. They search through the process buffer
  556. ;;; text looking for occurrences of the prompt.  Bound to M-P, M-N, and C-c R
  557. ;;; (uppercase P, N, and R) for now. Try'em out. Go with what you like...
  558.  
  559. ;;; comint-msearch-input-matching prompts for a string, not a regexp.
  560. ;;; This could be considered to be the wrong thing. I decided to keep it
  561. ;;; simple, and not make the user worry about regexps. This, of course,
  562. ;;; limits functionality.
  563.  
  564. ;;; These commands were deemed non-winning and have been commented out.
  565. ;;; Feel free to re-enable them if you like. -Olin 3/91
  566.  
  567. ;(defun comint-psearch-input ()
  568. ;  "Search forwards for next occurrence of prompt and skip to end of line.
  569. ;\(prompt is anything matching regexp comint-prompt-regexp)"
  570. ;  (interactive)
  571. ;  (if (re-search-forward comint-prompt-regexp (point-max) t)
  572. ;      (end-of-line)
  573. ;      (error "No occurrence of prompt found")))
  574. ;
  575. ;(defun comint-msearch-input ()
  576. ;  "Search backwards for previous occurrence of prompt and skip to end of line.
  577. ;Search starts from beginning of current line."
  578. ;  (interactive)
  579. ;  (let ((p (save-excursion
  580. ;         (beginning-of-line)
  581. ;         (cond ((re-search-backward comint-prompt-regexp (point-min) t)
  582. ;            (end-of-line)
  583. ;            (point))
  584. ;           (t nil)))))
  585. ;    (if p (goto-char p)
  586. ;    (error "No occurrence of prompt found"))))
  587. ;
  588. ;(defun comint-msearch-input-matching (str)
  589. ;  "Search backwards for occurrence of prompt followed by STRING.
  590. ;STRING is prompted for, and is NOT a regular expression."
  591. ;  (interactive (let ((s (read-from-minibuffer 
  592. ;             (format "Command (default %s): "
  593. ;                 comint-last-input-match))))
  594. ;         (list (if (string= s "") comint-last-input-match s))))
  595. ;; (interactive "sCommand: ")
  596. ;  (setq comint-last-input-match str) ; update default
  597. ;  (let* ((r (concat comint-prompt-regexp (regexp-quote str)))
  598. ;     (p (save-excursion
  599. ;          (beginning-of-line)
  600. ;          (cond ((re-search-backward r (point-min) t)
  601. ;             (end-of-line)
  602. ;             (point))
  603. ;            (t nil)))))
  604. ;    (if p (goto-char p)
  605. ;    (error "No match"))))
  606.  
  607. ;;;
  608. ;;; Similar input -- contributed by ccm and highly winning.
  609. ;;;
  610. ;;; Reenter input, removing back to the last insert point if it exists. 
  611. ;;;
  612. (defvar comint-last-similar-string "" 
  613.   "The string last used in a similar string search.")
  614. (defun comint-previous-similar-input (arg)
  615.   "Reenters the last input that matches the string typed so far.  If repeated 
  616. successively older inputs are reentered.  If arg is 1, it will go back
  617. in the history, if -1 it will go forward."
  618.   (interactive "p")
  619.   (if (not (comint-after-pmark-p))
  620.       (error "Not after process mark"))
  621.   (if (not (eq last-command 'comint-previous-similar-input))
  622.       (setq input-ring-index -1
  623.         comint-last-similar-string 
  624.         (buffer-substring 
  625.          (process-mark (get-buffer-process (current-buffer)))
  626.          (point))))
  627.   (let* ((size (length comint-last-similar-string))
  628.      (len (ring-length input-ring))
  629.      (n (+ input-ring-index arg))
  630.      entry)
  631.     (while (and (< n len) 
  632.         (or (< (length (setq entry (ring-ref input-ring n))) size)
  633.             (not (equal comint-last-similar-string 
  634.                 (substring entry 0 size)))))
  635.       (setq n (+ n arg)))
  636.     (cond ((< n len)
  637.        (setq input-ring-index n)
  638.        (if (eq last-command 'comint-previous-similar-input)
  639.            (delete-region (mark) (point)) ; repeat
  640.            (push-mark (point)))          ; 1st time
  641.        (insert (substring entry size)))
  642.       (t (message "Not found.") (ding) (sit-for 1)))
  643.     (message "%d" (1+ input-ring-index))))
  644.  
  645.  
  646. (defun comint-send-input () 
  647.   "Send input to process.  After the process output mark, sends all text
  648. from the process mark to point as input to the process.  Before the process
  649. output mark, calls value of variable comint-get-old-input to retrieve old
  650. input, copies it to the process mark, and sends it.  A terminal newline is
  651. also inserted into the buffer and sent to the process.  In either case, value
  652. of variable comint-input-sentinel is called on the input before sending it.
  653. The input is entered into the input history ring, if the value of variable
  654. comint-input-filter returns non-nil when called on the input.
  655.  
  656. If variable comint-eol-on-send is non-nil, then point is moved to the end of
  657. line before sending the input.
  658.  
  659. comint-get-old-input, comint-input-sentinel, and comint-input-filter are chosen
  660. according to the command interpreter running in the buffer. E.g.,
  661. If the interpreter is the csh,
  662.     comint-get-old-input is the default: take the current line, discard any
  663.         initial string matching regexp comint-prompt-regexp.
  664.     comint-input-sentinel monitors input for \"cd\", \"pushd\", and \"popd\" 
  665.         commands. When it sees one, it cd's the buffer.
  666.     comint-input-filter is the default: returns T if the input isn't all white
  667.     space.
  668.  
  669. If the comint is Lucid Common Lisp, 
  670.     comint-get-old-input snarfs the sexp ending at point.
  671.     comint-input-sentinel does nothing.
  672.     comint-input-filter returns NIL if the input matches input-filter-regexp,
  673.         which matches (1) all whitespace (2) :a, :c, etc.
  674.  
  675. Similarly for Soar, Scheme, etc.."
  676.   (interactive)
  677.   ;; Note that the input string does not include its terminal newline.
  678.   (let ((proc (get-buffer-process (current-buffer))))
  679.     (if (not proc) (error "Current buffer has no process")
  680.     (let* ((pmark (process-mark proc))
  681.            (pmark-val (marker-position pmark))
  682.            (input (if (>= (point) pmark-val)
  683.               (progn (if comint-eol-on-send (end-of-line))
  684.                  (buffer-substring pmark (point)))
  685.               (let ((copy (funcall comint-get-old-input)))
  686.                 (goto-char pmark)
  687.                 (insert copy)
  688.                 copy))))
  689.       (insert ?\n)
  690.       (if (funcall comint-input-filter input) (ring-insert input-ring input))
  691.       (funcall comint-input-sentinel input)
  692.       (funcall comint-input-sender proc input)
  693.       (set-marker (process-mark proc) (point))
  694.       (set-marker comint-last-input-end (point))))))
  695.  
  696. (defun comint-get-old-input-default ()
  697.   "Default for comint-get-old-input: take the current line, and discard
  698. any initial text matching comint-prompt-regexp."
  699.   (save-excursion
  700.     (beginning-of-line)
  701.     (comint-skip-prompt)
  702.     (let ((beg (point)))
  703.       (end-of-line)
  704.       (buffer-substring beg (point)))))
  705.  
  706. (defun comint-skip-prompt ()
  707.   "Skip past the text matching regexp comint-prompt-regexp. 
  708. If this takes us past the end of the current line, don't skip at all."
  709.   (let ((eol (save-excursion (end-of-line) (point))))
  710.     (if (and (looking-at comint-prompt-regexp)
  711.          (<= (match-end 0) eol))
  712.     (goto-char (match-end 0)))))
  713.  
  714.  
  715. (defun comint-after-pmark-p ()
  716.   "Is point after the process output marker?"
  717.   ;; Since output could come into the buffer after we looked at the point
  718.   ;; but before we looked at the process marker's value, we explicitly 
  719.   ;; serialise. This is just because I don't know whether or not emacs
  720.   ;; services input during execution of lisp commands.
  721.   (let ((proc-pos (marker-position
  722.            (process-mark (get-buffer-process (current-buffer))))))
  723.     (<= proc-pos (point))))
  724.  
  725. (defun comint-simple-send (proc string)
  726.   "Default function for sending to PROC input STRING.
  727. This just sends STRING plus a newline. To override this,
  728. set the hook COMINT-INPUT-SENDER."
  729.   (comint-send-string proc string)
  730.   (comint-send-string proc "\n"))
  731.  
  732. (defun comint-bol (arg)
  733.   "Goes to the beginning of line, then skips past the prompt, if any.
  734. If a prefix argument is given (\\[universal-argument]), then no prompt skip 
  735. -- go straight to column 0.
  736.  
  737. The prompt skip is done by skipping text matching the regular expression
  738. comint-prompt-regexp, a buffer local variable.
  739.  
  740. If you don't like this command, reset c-a to beginning-of-line 
  741. in your hook, comint-mode-hook."
  742.   (interactive "P")
  743.   (beginning-of-line)
  744.   (if (null arg) (comint-skip-prompt)))
  745.  
  746. ;;; These two functions are for entering text you don't want echoed or
  747. ;;; saved -- typically passwords to ftp, telnet, or somesuch.
  748. ;;; Just enter m-x send-invisible and type in your line.
  749.  
  750. (defun comint-read-noecho (prompt)
  751.   "Prompt the user with argument PROMPT. Read a single line of text
  752. without echoing, and return it. Note that the keystrokes comprising
  753. the text can still be recovered (temporarily) with \\[view-lossage]. This
  754. may be a security bug for some applications."
  755.   (let ((echo-keystrokes 0)
  756.     (answ "")
  757.     tem)
  758.     (if (and (stringp prompt) (not (string= (message prompt) "")))
  759.     (message prompt))
  760.     (while (not(or  (= (setq tem (read-char)) ?\^m)
  761.             (= tem ?\n)))
  762.       (setq answ (concat answ (char-to-string tem))))
  763.     (message "")
  764.     answ))
  765.  
  766. (defun send-invisible (str)
  767.   "Read a string without echoing, and send it to the process running
  768. in the current buffer. A new-line is additionally sent. String is not 
  769. saved on comint input history list.
  770. Security bug: your string can still be temporarily recovered with
  771. \\[view-lossage]."
  772. ; (interactive (list (comint-read-noecho "Enter non-echoed text")))
  773.   (interactive "P") ; Defeat snooping via C-x esc
  774.   (let ((proc (get-buffer-process (current-buffer))))
  775.     (if (not proc) (error "Current buffer has no process")
  776.     (comint-send-string proc
  777.                 (if (stringp str) str
  778.                 (comint-read-noecho "Enter non-echoed text")))
  779.     (comint-send-string proc "\n"))))
  780.  
  781.  
  782. ;;; Low-level process communication
  783.  
  784. (defvar comint-input-chunk-size 512
  785.   "*Long inputs send to comint processes are broken up into chunks of this size.
  786. If your process is choking on big inputs, try lowering the value.")
  787.  
  788. (defun comint-send-string (proc str)
  789.   "Send PROCESS the contents of STRING as input.
  790. This is equivalent to process-send-string, except that long input strings
  791. are broken up into chunks of size comint-input-chunk-size. Processes
  792. are given a chance to output between chunks. This can help prevent processes
  793. from hanging when you send them long inputs on some OS's."
  794.   (let* ((len (length str))
  795.      (i (min len comint-input-chunk-size)))
  796.     (process-send-string proc (substring str 0 i))
  797.     (while (< i len)
  798.       (let ((next-i (+ i comint-input-chunk-size)))
  799.     (accept-process-output)
  800.     (process-send-string proc (substring str i (min len next-i)))
  801.     (setq i next-i)))))
  802.  
  803. (defun comint-send-region (proc start end)
  804.   "Sends to PROC the region delimited by START and END.
  805. This is a replacement for process-send-region that tries to keep
  806. your process from hanging on long inputs. See comint-send-string."
  807.   (comint-send-string proc (buffer-substring start end)))
  808.  
  809.  
  810. ;;; Random input hackage
  811.  
  812. (defun comint-kill-output ()
  813.   "Kill all output from interpreter since last input."
  814.   (interactive)
  815.   (let ((pmark (process-mark (get-buffer-process (current-buffer)))))
  816.     (kill-region comint-last-input-end pmark)
  817.     (goto-char pmark)    
  818.     (insert "*** output flushed ***\n")
  819.     (set-marker pmark (point))))
  820.  
  821. (defun comint-show-output ()
  822.   "Display start of this batch of interpreter output at top of window.
  823. Also put cursor there."
  824.   (interactive)
  825.   (goto-char comint-last-input-end)
  826.   (backward-char)
  827.   (beginning-of-line)
  828.   (set-window-start (selected-window) (point))
  829.   (end-of-line))
  830.  
  831. (defun comint-interrupt-subjob ()
  832.   "Interrupt the current subjob."
  833.   (interactive)
  834.   (interrupt-process nil comint-ptyp))
  835.  
  836. (defun comint-kill-subjob ()
  837.   "Send kill signal to the current subjob."
  838.   (interactive)
  839.   (kill-process nil comint-ptyp))
  840.  
  841. (defun comint-quit-subjob ()
  842.   "Send quit signal to the current subjob."
  843.   (interactive)
  844.   (quit-process nil comint-ptyp))
  845.  
  846. (defun comint-stop-subjob ()
  847.   "Stop the current subjob.
  848. WARNING: if there is no current subjob, you can end up suspending
  849. the top-level process running in the buffer. If you accidentally do
  850. this, use \\[comint-continue-subjob] to resume the process. (This
  851. is not a problem with most shells, since they ignore this signal.)"
  852.   (interactive)
  853.   (stop-process nil comint-ptyp))
  854.  
  855. (defun comint-continue-subjob ()
  856.   "Send CONT signal to process buffer's process group.
  857. Useful if you accidentally suspend the top-level process."
  858.   (interactive)
  859.   (continue-process nil comint-ptyp))
  860.  
  861. (defun comint-kill-input ()
  862.   "Kill all text from last stuff output by interpreter to point."
  863.   (interactive)
  864.   (let* ((pmark (process-mark (get-buffer-process (current-buffer))))
  865.      (p-pos (marker-position pmark)))
  866.     (if (> (point) p-pos)
  867.     (kill-region pmark (point)))))
  868.  
  869. (defun comint-delchar-or-maybe-eof (arg)
  870.   "Delete ARG characters forward, or send an EOF to process if at end of buffer."
  871.   (interactive "p")
  872.   (if (eobp)
  873.       (process-send-eof)
  874.       (delete-char arg)))
  875.  
  876.  
  877.  
  878.  
  879. ;;; Support for source-file processing commands.
  880. ;;;============================================================================
  881. ;;; Many command-interpreters (e.g., Lisp, Scheme, Soar) have
  882. ;;; commands that process files of source text (e.g. loading or compiling
  883. ;;; files). So the corresponding process-in-a-buffer modes have commands
  884. ;;; for doing this (e.g., lisp-load-file). The functions below are useful
  885. ;;; for defining these commands.
  886. ;;;
  887. ;;; Alas, these guys don't do exactly the right thing for Lisp, Scheme
  888. ;;; and Soar, in that they don't know anything about file extensions.
  889. ;;; So the compile/load interface gets the wrong default occasionally.
  890. ;;; The load-file/compile-file default mechanism could be smarter -- it
  891. ;;; doesn't know about the relationship between filename extensions and
  892. ;;; whether the file is source or executable. If you compile foo.lisp
  893. ;;; with compile-file, then the next load-file should use foo.bin for
  894. ;;; the default, not foo.lisp. This is tricky to do right, particularly
  895. ;;; because the extension for executable files varies so much (.o, .bin,
  896. ;;; .lbin, .mo, .vo, .ao, ...).
  897.  
  898.  
  899. ;;; COMINT-SOURCE-DEFAULT -- determines defaults for source-file processing
  900. ;;; commands.
  901. ;;;
  902. ;;; COMINT-CHECK-SOURCE -- if FNAME is in a modified buffer, asks you if you
  903. ;;; want to save the buffer before issuing any process requests to the command
  904. ;;; interpreter.
  905. ;;;
  906. ;;; COMINT-GET-SOURCE -- used by the source-file processing commands to prompt
  907. ;;; for the file to process.
  908.  
  909. ;;; (COMINT-SOURCE-DEFAULT previous-dir/file source-modes)
  910. ;;;============================================================================
  911. ;;; This function computes the defaults for the load-file and compile-file
  912. ;;; commands for tea, soar, cmulisp, and cmuscheme modes. 
  913. ;;; 
  914. ;;; - PREVIOUS-DIR/FILE is a pair (directory . filename) from the last 
  915. ;;; source-file processing command. NIL if there hasn't been one yet.
  916. ;;; - SOURCE-MODES is a list used to determine what buffers contain source
  917. ;;; files: if the major mode of the buffer is in SOURCE-MODES, it's source.
  918. ;;; Typically, (lisp-mode) or (scheme-mode).
  919. ;;; 
  920. ;;; If the command is given while the cursor is inside a string, *and*
  921. ;;; the string is an existing filename, *and* the filename is not a directory,
  922. ;;; then the string is taken as default. This allows you to just position
  923. ;;; your cursor over a string that's a filename and have it taken as default.
  924. ;;;
  925. ;;; If the command is given in a file buffer whose major mode is in
  926. ;;; SOURCE-MODES, then the the filename is the default file, and the
  927. ;;; file's directory is the default directory.
  928. ;;; 
  929. ;;; If the buffer isn't a source file buffer (e.g., it's the process buffer),
  930. ;;; then the default directory & file are what was used in the last source-file
  931. ;;; processing command (i.e., PREVIOUS-DIR/FILE).  If this is the first time
  932. ;;; the command has been run (PREVIOUS-DIR/FILE is nil), the default directory
  933. ;;; is the cwd, with no default file. (\"no default file\" = nil)
  934. ;;; 
  935. ;;; SOURCE-REGEXP is typically going to be something like (tea-mode)
  936. ;;; for T programs, (lisp-mode) for Lisp programs, (soar-mode lisp-mode)
  937. ;;; for Soar programs, etc.
  938. ;;; 
  939. ;;; The function returns a pair: (default-directory . default-file).
  940.  
  941. (defun comint-source-default (previous-dir/file source-modes)
  942.   (cond ((and buffer-file-name (memq major-mode source-modes))
  943.      (cons (file-name-directory    buffer-file-name)
  944.            (file-name-nondirectory buffer-file-name)))
  945.     (previous-dir/file)
  946.     (t
  947.      (cons default-directory nil))))
  948.  
  949.  
  950. ;;; (COMINT-CHECK-SOURCE fname)
  951. ;;;============================================================================
  952. ;;; Prior to loading or compiling (or otherwise processing) a file (in the CMU
  953. ;;; process-in-a-buffer modes), this function can be called on the filename.
  954. ;;; If the file is loaded into a buffer, and the buffer is modified, the user
  955. ;;; is queried to see if he wants to save the buffer before proceeding with
  956. ;;; the load or compile.
  957.  
  958. (defun comint-check-source (fname)
  959.   (let ((buff (get-file-buffer fname)))
  960.     (if (and buff
  961.          (buffer-modified-p buff)
  962.          (y-or-n-p (format "Save buffer %s first? "
  963.                    (buffer-name buff))))
  964.     ;; save BUFF.
  965.     (let ((old-buffer (current-buffer)))
  966.       (set-buffer buff)
  967.       (save-buffer)
  968.       (set-buffer old-buffer)))))
  969.  
  970.  
  971. ;;; (COMINT-GET-SOURCE prompt prev-dir/file source-modes mustmatch-p)
  972. ;;;============================================================================
  973. ;;; COMINT-GET-SOURCE is used to prompt for filenames in command-interpreter
  974. ;;; commands that process source files (like loading or compiling a file).
  975. ;;; It prompts for the filename, provides a default, if there is one,
  976. ;;; and returns the result filename.
  977. ;;; 
  978. ;;; See COMINT-SOURCE-DEFAULT for more on determining defaults.
  979. ;;; 
  980. ;;; PROMPT is the prompt string. PREV-DIR/FILE is the (directory . file) pair
  981. ;;; from the last source processing command.  SOURCE-MODES is a list of major
  982. ;;; modes used to determine what file buffers contain source files.  (These
  983. ;;; two arguments are used for determining defaults). If MUSTMATCH-P is true,
  984. ;;; then the filename reader will only accept a file that exists.
  985. ;;; 
  986. ;;; A typical use:
  987. ;;; (interactive (comint-get-source "Compile file: " prev-lisp-dir/file
  988. ;;;                                 '(lisp-mode) t))
  989.  
  990. ;;; This is pretty stupid about strings. It decides we're in a string
  991. ;;; if there's a quote on both sides of point on the current line.
  992. (defun comint-extract-string ()
  993.   "Returns string around point that starts the current line or nil." 
  994.   (save-excursion
  995.     (let* ((point (point))
  996.        (bol (progn (beginning-of-line) (point)))
  997.        (eol (progn (end-of-line) (point)))
  998.        (start (progn (goto-char point) 
  999.              (and (search-backward "\"" bol t) 
  1000.                   (1+ (point)))))
  1001.        (end (progn (goto-char point)
  1002.                (and (search-forward "\"" eol t)
  1003.                 (1- (point))))))
  1004.       (and start end
  1005.        (buffer-substring start end)))))
  1006.  
  1007. (defun comint-get-source (prompt prev-dir/file source-modes mustmatch-p)
  1008.   (let* ((def (comint-source-default prev-dir/file source-modes))
  1009.          (stringfile (comint-extract-string))
  1010.      (sfile-p (and stringfile
  1011.                (condition-case ()
  1012.                (file-exists-p stringfile)
  1013.              (error nil))
  1014.                (not (file-directory-p stringfile))))
  1015.      (defdir  (if sfile-p (file-name-directory stringfile)
  1016.                       (car def)))
  1017.      (deffile (if sfile-p (file-name-nondirectory stringfile)
  1018.                       (cdr def)))
  1019.      (ans (read-file-name (if deffile (format "%s(default %s) "
  1020.                           prompt    deffile)
  1021.                   prompt)
  1022.                   defdir
  1023.                   (concat defdir deffile)
  1024.                   mustmatch-p)))
  1025.     (list (expand-file-name (substitute-in-file-name ans)))))
  1026.  
  1027. ;;; I am somewhat divided on this string-default feature. It seems
  1028. ;;; to violate the principle-of-least-astonishment, in that it makes
  1029. ;;; the default harder to predict, so you actually have to look and see
  1030. ;;; what the default really is before choosing it. This can trip you up.
  1031. ;;; On the other hand, it can be useful, I guess. I would appreciate feedback
  1032. ;;; on this.
  1033. ;;;     -Olin
  1034.  
  1035.  
  1036. ;;; Simple process query facility.
  1037. ;;; ===========================================================================
  1038. ;;; This function is for commands that want to send a query to the process
  1039. ;;; and show the response to the user. For example, a command to get the
  1040. ;;; arglist for a Common Lisp function might send a "(arglist 'foo)" query
  1041. ;;; to an inferior Common Lisp process.
  1042. ;;; 
  1043. ;;; This simple facility just sends strings to the inferior process and pops
  1044. ;;; up a window for the process buffer so you can see what the process
  1045. ;;; responds with.  We don't do anything fancy like try to intercept what the
  1046. ;;; process responds with and put it in a pop-up window or on the message
  1047. ;;; line. We just display the buffer. Low tech. Simple. Works good.
  1048.  
  1049. ;;; Send to the inferior process PROC the string STR. Pop-up but do not select
  1050. ;;; a window for the inferior process so that its response can be seen.
  1051. (defun comint-proc-query (proc str)
  1052.   (let* ((proc-buf (process-buffer proc))
  1053.      (proc-mark (process-mark proc)))
  1054.     (display-buffer proc-buf)
  1055.     (set-buffer proc-buf) ; but it's not the selected *window*
  1056.     (let ((proc-win (get-buffer-window proc-buf))
  1057.       (proc-pt (marker-position proc-mark)))
  1058.       (comint-send-string proc str) ; send the query
  1059.       (accept-process-output proc)  ; wait for some output
  1060.       ;; Try to position the proc window so you can see the answer.
  1061.       ;; This is bogus code. If you delete the (sit-for 0), it breaks.
  1062.       ;; I don't know why. Wizards invited to improve it.
  1063.       (if (not (pos-visible-in-window-p proc-pt proc-win))
  1064.       (let ((opoint (window-point proc-win)))
  1065.         (set-window-point proc-win proc-mark) (sit-for 0)
  1066.         (if (not (pos-visible-in-window-p opoint proc-win))
  1067.         (push-mark opoint)
  1068.         (set-window-point proc-win opoint)))))))
  1069.  
  1070.  
  1071. ;;; Filename completion in a buffer
  1072. ;;; ===========================================================================
  1073. ;;; Useful completion functions, courtesy of the Ergo group.
  1074. ;;; M-<Tab> will complete the filename at the cursor as much as possible
  1075. ;;; M-? will display a list of completions in the help buffer.
  1076.  
  1077. ;;; Three commands:
  1078. ;;; comint-dynamic-complete        Complete filename at point.
  1079. ;;; comint-dynamic-list-completions    List completions in help buffer.
  1080. ;;; comint-replace-by-expanded-filename    Expand and complete filename at point;
  1081. ;;;                    replace with expanded/completed name.
  1082.  
  1083. ;;; These are not installed in the comint-mode keymap. But they are
  1084. ;;; available for people who want them. Shell-mode installs them:
  1085. ;;; (define-key cmushell-mode-map "\M-\t" 'comint-dynamic-complete)
  1086. ;;; (define-key cmushell-mode-map "\M-?"  'comint-dynamic-list-completions)))
  1087. ;;;
  1088. ;;; Commands like this are fine things to put in load hooks if you
  1089. ;;; want them present in specific modes. Example:
  1090. ;;; (setq cmushell-load-hook
  1091. ;;;       '((lambda () (define-key lisp-mode-map "\M-\t"
  1092. ;;;                   'comint-replace-by-expanded-filename))))
  1093. ;;;          
  1094.  
  1095.  
  1096. (defun comint-match-partial-pathname ()
  1097.   "Returns the filename at point or causes an error."
  1098.   (save-excursion
  1099.     (if (re-search-backward "[^~/A-Za-z0-9---_.$#,=]" nil 'move)
  1100.     (forward-char 1))
  1101.     ;; Anchor the search forwards.
  1102.     (if (not (looking-at "[~/A-Za-z0-9---_.$#,=]")) (error ""))
  1103.     (re-search-forward "[~/A-Za-z0-9---_.$#,=]+")
  1104.     (substitute-in-file-name
  1105.      (buffer-substring (match-beginning 0) (match-end 0)))))
  1106.  
  1107.  
  1108. (defun comint-replace-by-expanded-filename ()
  1109. "Replace the filename at point with an expanded, canonicalised, and
  1110. completed replacement.
  1111. \"Expanded\" means environment variables (e.g., $HOME) and ~'s are
  1112. replaced with the corresponding directories.  \"Canonicalised\" means ..
  1113. and \. are removed, and the filename is made absolute instead of relative.
  1114. See functions expand-file-name and substitute-in-file-name. See also
  1115. comint-dynamic-complete."
  1116.   (interactive)
  1117.   (let* ((pathname (comint-match-partial-pathname))
  1118.      (pathdir (file-name-directory pathname))
  1119.      (pathnondir (file-name-nondirectory pathname))
  1120.      (completion (file-name-completion pathnondir
  1121.                        (or pathdir default-directory))))
  1122.     (cond ((null completion)
  1123.        (message "No completions of %s." pathname)
  1124.        (ding))
  1125.       ((eql completion t)
  1126.        (message "Unique completion."))
  1127.       (t                ; this means a string was returned.
  1128.        (delete-region (match-beginning 0) (match-end 0))
  1129.        (insert (expand-file-name (concat pathdir completion)))))))
  1130.  
  1131.  
  1132. (defun comint-dynamic-complete ()
  1133.   "Dynamically complete the filename at point.
  1134. This function is similar to comint-replace-by-expanded-filename, except
  1135. that it won't change parts of the filename already entered in the buffer; 
  1136. it just adds completion characters to the end of the filename."
  1137.   (interactive)
  1138.   (let* ((pathname (comint-match-partial-pathname))
  1139.      (pathdir (file-name-directory pathname))
  1140.      (pathnondir (file-name-nondirectory pathname))
  1141.      (completion (file-name-completion  pathnondir
  1142.                        (or pathdir default-directory))))
  1143.     (cond ((null completion)
  1144.        (message "No completions of %s." pathname)
  1145.        (ding))
  1146.       ((eql completion t)
  1147.        (message "Unique completion."))
  1148.       (t                ; this means a string was returned.
  1149.        (goto-char (match-end 0))
  1150.        (insert (substring completion (length pathnondir)))))))
  1151.  
  1152. (defun comint-dynamic-list-completions ()
  1153.   "List in help buffer all possible completions of the filename at point."
  1154.   (interactive)
  1155.   (let* ((pathname (comint-match-partial-pathname))
  1156.      (pathdir (file-name-directory pathname))
  1157.      (pathnondir (file-name-nondirectory pathname))
  1158.      (completions
  1159.       (file-name-all-completions pathnondir
  1160.                      (or pathdir default-directory))))
  1161.     (cond ((null completions)
  1162.        (message "No completions of %s." pathname)
  1163.        (ding))
  1164.       (t
  1165.        (let ((conf (current-window-configuration)))
  1166.          (with-output-to-temp-buffer "*Help*"
  1167.            (display-completion-list completions))
  1168.          (sit-for 0)
  1169.          (message "Hit space to flush.")
  1170.          (let ((ch (read-char)))
  1171.            (if (= ch ?\ )
  1172.            (set-window-configuration conf)
  1173.            (setq unread-command-char ch))))))))
  1174.  
  1175. ; Ergo bindings
  1176. ; (global-set-key "\M-\t" 'comint-replace-by-expanded-filename)
  1177. ; (global-set-key "\M-?" 'comint-dynamic-list-completions)
  1178. ; (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1179.  
  1180. ;;; Converting process modes to use comint mode
  1181. ;;; ===========================================================================
  1182. ;;; Several gnu packages (tex-mode, background, dbx, gdb, kermit, prolog, 
  1183. ;;; telnet are some) use the shell package as clients. Most of them would
  1184. ;;; be better off using the comint package, but they predate it. 
  1185. ;;;
  1186. ;;; Altering these packages to use comint mode should greatly
  1187. ;;; improve their functionality, and is fairly easy.
  1188. ;;; 
  1189. ;;; Renaming variables
  1190. ;;; Most of the work is renaming variables and functions. These are the common
  1191. ;;; ones:
  1192. ;;; Local variables:
  1193. ;;;     last-input-end        comint-last-input-end
  1194. ;;;    last-input-start    <unnecessary>
  1195. ;;;    shell-prompt-pattern    comint-prompt-regexp
  1196. ;;;     shell-set-directory-error-hook <no equivalent>
  1197. ;;; Miscellaneous:
  1198. ;;;    shell-set-directory    <unnecessary>
  1199. ;;;     shell-mode-map        comint-mode-map
  1200. ;;; Commands:
  1201. ;;;    shell-send-input    comint-send-input
  1202. ;;;    shell-send-eof        comint-delchar-or-maybe-eof
  1203. ;;;     kill-shell-input    comint-kill-input
  1204. ;;;    interrupt-shell-subjob    comint-interrupt-subjob
  1205. ;;;    stop-shell-subjob    comint-stop-subjob
  1206. ;;;    quit-shell-subjob    comint-quit-subjob
  1207. ;;;    kill-shell-subjob    comint-kill-subjob
  1208. ;;;    kill-output-from-shell    comint-kill-output
  1209. ;;;    show-output-from-shell    comint-show-output
  1210. ;;;    copy-last-shell-input    Use comint-previous-input/comint-next-input
  1211. ;;;
  1212. ;;; LAST-INPUT-START is no longer necessary because inputs are stored on the
  1213. ;;; input history ring. SHELL-SET-DIRECTORY is gone, its functionality taken
  1214. ;;; over by SHELL-DIRECTORY-TRACKER, the shell mode's comint-input-sentinel.
  1215. ;;; Comint mode does not provide functionality equivalent to 
  1216. ;;; shell-set-directory-error-hook; it is gone.
  1217. ;;; 
  1218. ;;; If you are implementing some process-in-a-buffer mode, called foo-mode, do
  1219. ;;; *not* create the comint-mode local variables in your foo-mode function.
  1220. ;;; This is not modular.  Instead, call comint-mode, and let *it* create the
  1221. ;;; necessary comint-specific local variables. Then create the
  1222. ;;; foo-mode-specific local variables in foo-mode.  Set the buffer's keymap to
  1223. ;;; be foo-mode-map, and its mode to be foo-mode.  Set the comint-mode hooks
  1224. ;;; (comint-prompt-regexp, comint-input-filter, comint-input-sentinel,
  1225. ;;; comint-get-old-input) that need to be different from the defaults.  Call
  1226. ;;; foo-mode-hook, and you're done. Don't run the comint-mode hook yourself;
  1227. ;;; comint-mode will take care of it. The following example, from cmushell.el,
  1228. ;;; is typical:
  1229. ;;; 
  1230. ;;; (defun shell-mode ()
  1231. ;;;   (interactive)
  1232. ;;;   (comint-mode)
  1233. ;;;   (setq comint-prompt-regexp shell-prompt-pattern)
  1234. ;;;   (setq major-mode 'shell-mode)
  1235. ;;;   (setq mode-name "Shell")
  1236. ;;;   (cond ((not shell-mode-map)
  1237. ;;;          (setq shell-mode-map (full-copy-sparse-keymap comint-mode-map))
  1238. ;;;          (define-key shell-mode-map "\M-\t" 'comint-dynamic-complete)
  1239. ;;;          (define-key shell-mode-map "\M-?"
  1240. ;;;                      'comint-dynamic-list-completions)))
  1241. ;;;   (use-local-map shell-mode-map)
  1242. ;;;   (make-local-variable 'shell-directory-stack)
  1243. ;;;   (setq shell-directory-stack nil)
  1244. ;;;   (setq comint-input-sentinel 'shell-directory-tracker)
  1245. ;;;   (run-hooks 'shell-mode-hook))
  1246. ;;;
  1247. ;;;
  1248. ;;; Note that make-comint is different from make-shell in that it
  1249. ;;; doesn't have a default program argument. If you give make-shell
  1250. ;;; a program name of NIL, it cleverly chooses one of explicit-shell-name,
  1251. ;;; $ESHELL, $SHELL, or /bin/sh. If you give make-comint a program argument
  1252. ;;; of NIL, it barfs. Adjust your code accordingly...
  1253. ;;;
  1254.  
  1255. ;;; Do the user's customisation...
  1256.  
  1257. (defvar comint-load-hook nil
  1258.   "This hook is run when comint is loaded in.
  1259. This is a good place to put keybindings.")
  1260.     
  1261. (run-hooks 'comint-load-hook)
  1262.  
  1263. ;;; Change log:
  1264. ;;; 9/12/89 
  1265. ;;;  - Souped up the filename expansion procedures.
  1266. ;;;    Doc strings are much clearer and more detailed.
  1267. ;;;    Fixed a bug where doing a filename completion when the point
  1268. ;;;    was in the middle of the filename instead of at the end would lose.
  1269. ;;;
  1270. ;;; 2/17/90 
  1271. ;;;  - Souped up the command history stuff so that text inserted
  1272. ;;;    by comint-previous-input-matching is removed by following
  1273. ;;;    command history recalls. comint-next/previous-input-matching
  1274. ;;;    is now much more smoothly integrated w/the command history stuff.
  1275. ;;;  - Added comint-eol-on-send flag and comint-input-sender hook.
  1276. ;;;    Comint-input-sender based on code contributed by Jeff Peck
  1277. ;;;    (peck@sun.com).
  1278. ;;;
  1279. ;;; 3/13/90 ccm@cmu.cs.edu
  1280. ;;;  - Added comint-previous-similar-input for looking up similar inputs.
  1281. ;;;  - Added comint-send-and-get-output to allow snarfing input from
  1282. ;;;    buffer. 
  1283. ;;;  - Added the ability to pick up a source file by positioning over
  1284. ;;;    a string in comint-get-source.
  1285. ;;;  - Added add-hook to make it a little easier for the user to use
  1286. ;;;    multiple hooks.
  1287. ;;;  
  1288. ;;; 5/22/90 shivers
  1289. ;;; - Moved Chris' multiplexed ipc stuff to comint-ipc.el.
  1290. ;;; - Altered Chris' comint-get-source string feature. The string
  1291. ;;;   is only offered as a default if it names an existing file.
  1292. ;;; - Changed comint-exec to directly crank up the process, instead
  1293. ;;;   of calling the env program. This made background.el happy.
  1294. ;;; - Added new buffer-local var comint-ptyp. The problem is that
  1295. ;;;   the signalling functions don't work as advertised. If you are
  1296. ;;;   communicating via pipes, the CURRENT-GROUP arg is supposed to
  1297. ;;;   be ignored, but, unfortunately it seems to be the case that you
  1298. ;;;   must pass a NIL for this arg in the pipe case. COMINT-PTYP
  1299. ;;;   is a flag that tells whether the process is communicating
  1300. ;;;   via pipes or a pty. The comint signalling functions use it
  1301. ;;;   to determine the necessary CURRENT-GROUP arg value. The bug
  1302. ;;;   has been reported to the Gnu folks.
  1303. ;;; - comint-dynamic-complete flushes the help window if you hit space
  1304. ;;;   after you execute it.
  1305. ;;; - Added functions comint-send-string, comint-send-region and var 
  1306. ;;;   comint-input-chunk-size.  comint-send-string tries to prevent processes
  1307. ;;;   from hanging when you send them long strings by breaking them into
  1308. ;;;   chunks and allowing process output between chunks. I got the idea from
  1309. ;;;   Eero Simoncelli's Common Lisp package. Note that using
  1310. ;;;   comint-send-string means that the process buffer's contents can change
  1311. ;;;   during a call!  If you depend on process output only happening between
  1312. ;;;   toplevel commands, this could be a problem. In such a case, use
  1313. ;;;   process-send-string instead. If this is a problem for people, I'd like
  1314. ;;;   to hear about it.
  1315. ;;; - Added comint-proc-query as a simple mechanism for commands that
  1316. ;;;   want to query an inferior process and display its response. For a
  1317. ;;;   typical use, see lisp-show-arglist in cmulisp.el.
  1318. ;;; - Added constant comint-version, which is now "2.01".
  1319. ;;;
  1320. ;;; 6/14/90 shivers
  1321. ;;; - Had comint-update-env defined twice. Removed extra copy. Also
  1322. ;;;   renamed mem to be comint-mem, for modularity. The duplication
  1323. ;;;   was reported by Michael Meissner.
  1324. ;;; 6/16/90 shivers
  1325. ;;; - Emacs has two different mechanisms for maintaining the process
  1326. ;;;   environment, determined at compile time by the MAINTAIN-ENVIRONMENT
  1327. ;;;   #define. One uses the process-environment global variable, and
  1328. ;;;   one uses a getenv/setenv interface. comint-exec assumed the
  1329. ;;;   process-environment interface; it has been generalised (with
  1330. ;;;   comint-exec-1) to handle both cases. Pretty bogus. We could,
  1331. ;;;   of course, skip all this and just use the etc/env program to
  1332. ;;;   handle the environment tweaking, but that obscures process
  1333. ;;;   queries that other modules (like background.el) depend on. etc/env
  1334. ;;;   is also fairly bogus. This bug, and some of the fix code was
  1335. ;;;   reported by Dan Pierson.
  1336. ;;;
  1337. ;;; 9/5/90 shivers
  1338. ;;; - Changed make-variable-buffer-local's to make-local-variable's.
  1339. ;;;   This leaves non-comint-mode buffers alone. Stephane Payrard
  1340. ;;;   reported the sloppy useage.
  1341. ;;; - You can now go from comint-previous-similar-input to
  1342. ;;;   comint-previous-input with no problem.
  1343. ;;;
  1344. ;;; 12/21/90 shivers
  1345. ;;; - Added a condition-case to comint-get-source. Bogus strings
  1346. ;;;   beginning with ~ were making the file-exists-p barf.
  1347. ;;; - Added "=" to the set of chars recognised by file completion
  1348. ;;;   as constituting a filename.
  1349. ;;;
  1350. ;;; 1/90 shivers
  1351. ;;; These changes comprise release 2.02:
  1352. ;;; - Removed the kill-all-local-variables in comint-mode. This
  1353. ;;;   made it impossible for client modes to set things before calling
  1354. ;;;   comint-mode. (In particular, it messed up ilisp.el) In general,
  1355. ;;;   the client mode should be responsible for a k-a-l-v's.
  1356. ;;; - Fixed comint-match-partial-pathname so that it works in
  1357. ;;;   more cases: if the filename begins at the start-of-buffer;
  1358. ;;;   if point is on the first char of the filename. Just a question
  1359. ;;;   of getting the tricky bits right.
  1360. ;;; - Added a hook, comint-exec-hook that is run each time a process
  1361. ;;;   is cranked up. Useful for things like process-kill-without-query.
  1362. ;;;
  1363. ;;; These two were pointed out by tale:
  1364. ;;; - Improved the doc string in comint-send-input a little bit.
  1365. ;;; - Tweaked make-comint to check process status with comint-check-proc
  1366. ;;;   instead of equivalent inline code. 
  1367. ;;;
  1368. ;;; - Prompt-search history commands have been commented out. I never
  1369. ;;;   liked them; I don't think anyone used them.
  1370. ;;; - Made comint-exec-hook a local var, as it should have been.
  1371. ;;;   (This way, for instance, you can have cmushell procs kill-w/o-query,
  1372. ;;;    but let Scheme procs be default.)
  1373.